package chapter_3.frame;

import java.io.*;

/**
 * 基于显式长度的方法来将实现消息成帧
 *
 * @author fulv
 */
public class LengthFramer implements Framer {

    private static final int MESSAGEMAXLENGTH = 65536;

    private DataInputStream in;

    //public LengthFramer(){}
    public LengthFramer(DataInputStream in) {
        this.in = in;
    }

    @Override
    public void frameMsg(byte[] msg, OutputStream out) throws IOException {
        if (msg.length > MESSAGEMAXLENGTH) {
            throw new IOException("传入的消息超出最大长度");
        }
        int msgLength = msg.length;
        //将消息长度按照字节大端序写入输出流中
        out.write((msgLength >> 8) & 0xFF);
        out.write(msgLength & 0xFF);
        //将消息写入输出流
        out.write(msg);
        out.flush();
    }


    @Override
    public byte[] nextMsg() throws IOException {
        int length;
        byte[] msg = null;
        try {
            //从输入流中读取两个字节，作为大端序的整型值解释，表示消息长度
            length = in.readUnsignedShort();
        } catch (EOFException e) {
            return null;
        }
        //存放从输入流中读取出的消息字节数组
        msg = new byte[length];
        //readFully多次调用read方法直到读取到指定长度的数组消息或者读取到-1返回
        in.readFully(msg);
        return msg;
    }
}
